import os
import sys
from pathlib import Path

def convert_svg_to_ico():
    """将SVG图标转换为ICO格式"""
    svg_path = Path("resources/icon.svg")
    ico_path = Path("resources/icon.ico")
    
    if not svg_path.exists():
        print(f"错误: SVG图标文件不存在: {svg_path}")
        return False
    
    if ico_path.exists():
        print(f"ICO图标文件已存在: {ico_path}")
        return True
    
    try:
        # 尝试使用cairosvg (需要安装)
        try:
            import cairosvg
            from PIL import Image
            
            print("使用cairosvg转换SVG到PNG...")
            png_temp = "temp_icon.png"
            cairosvg.svg2png(url=str(svg_path), write_to=png_temp, output_width=256, output_height=256)
            
            print("使用Pillow转换PNG到ICO...")
            img = Image.open(png_temp)
            img.save(str(ico_path))
            
            # 清理临时文件
            os.remove(png_temp)
            print(f"转换成功! 图标已保存到: {ico_path}")
            return True
            
        except ImportError:
            print("cairosvg未安装，尝试使用其他方法...")
        
        # 尝试使用Inkscape (如果已安装)
        inkscape_paths = [
            "inkscape",  # 在PATH中
            "C:\\Program Files\\Inkscape\\bin\\inkscape.exe",
            "C:\\Program Files\\Inkscape\\inkscape.exe"
        ]
        
        for inkscape_path in inkscape_paths:
            try:
                import subprocess
                png_temp = "temp_icon.png"
                
                # 使用Inkscape转换SVG到PNG
                print(f"尝试使用Inkscape: {inkscape_path}")
                subprocess.run(
                    [inkscape_path, str(svg_path), "-o", png_temp, "-w", "256", "-h", "256"],
                    check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                )
                
                # 使用Pillow转换PNG到ICO
                from PIL import Image
                img = Image.open(png_temp)
                img.save(str(ico_path))
                
                # 清理临时文件
                os.remove(png_temp)
                print(f"转换成功! 图标已保存到: {ico_path}")
                return True
                
            except (subprocess.SubprocessError, FileNotFoundError):
                print(f"Inkscape未找到或执行失败: {inkscape_path}")
                continue
            except ImportError:
                print("Pillow未安装，无法完成转换")
                break
        
        # 如果以上方法都失败，提供安装建议
        print("\n无法转换SVG到ICO。请安装必要的依赖:")
        print("1. pip install pillow cairosvg")
        print("或")
        print("2. 安装Inkscape (https://inkscape.org/)")
        print("\n然后重新运行此脚本。")
        return False
        
    except Exception as e:
        print(f"转换过程中出错: {str(e)}")
        return False

if __name__ == "__main__":
    # 确保resources目录存在
    os.makedirs("resources", exist_ok=True)
    
    # 执行转换
    convert_svg_to_ico()